<?php 
namespace auth;

use app\index\model\User;
use think\Session;
use think\Cookie;
use crypt\Mcrypt;

/**
* auth登录
*/
class Auth
{

            public static $user;
	/**
	* 检查是否登录
	*/
	public static function check()
	{
            	   if (Session::has('user')) {
                    self::$user = Session::get('user');
                    return true;
    	   } else {
    	       $token = @unserialize(Mcrypt::deAES(Cookie::get('token')));
                    if (!$token) {
                        return false;
                    }
                    $id = $token['id'];
                    if ($token['expiration'] > time() && $token['ip'] == $_SERVER['REMOTE_ADDR']) {
                        $user = User::where('id',$id)->find()->toArray();
                        if ($user) {
                            self::$user = $user;
                            return true;
                        }
                    }
    	       return false;
    	   }
	}
            /**
            * 登录
            * @param  array $user 用户信息数组
            * @param boole $is_remember 是否记住密码
            */
            public static function login($user,$is_remember = false)
            {
                Session::set('user',$user);
                Cookie::delete('token');
                $data = ['login_time'=>time(),
                    'login_ip'=>$_SERVER['REMOTE_ADDR']
                    ];
                if ($is_remember) {
                    $token = Mcrypt::enAES(serialize([
                        'id' => $user['id'],
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'expiration' => time()+3600*24*7,
                        'salt' => config('app_key')
                        ]));
                    Cookie::set('token',$token,3600*24*7);
                    $data['remember_token'] = $token;
                }
                User::where('id',$user['id'])->update($data);
            }
	/**
	* 退出登录
	*/
	public static function logout()
	{
	   Session::delete('user');
                Cookie::delete('token');
	}
	/**
	* 获取用户信息
	*/
	public static function user()
	{    
                if (self::check()) {
                    return self::$user;
                }
                return false;
	}
	/**
	* 验证用户
             *@param   array $data 验证的数据选项 password
	*/
	public static function attempt($data, $is_remember = false)
	{
                $password = $data['password'];
                unset($data['password']);
	   $user = User::where($data)->find()->toArray();
            	   if (!empty($user) && password_verify($password,$user['password'])) {
                    self::login($user, $is_remember);
            	       return true;
            	   }
            	   return false;
	}
}
